<?php
/* 
 *prepare for the goods to shipped
 */
class PrepareAction extends CommonAction {
    public function _filter(&$map) {
        if( $_REQUEST['remark'] != '' )
          $map['remark'] = trim($_REQUEST['remark']);

        if( $_REQUEST['logino'] != '' )
          $map['logino'] = array('like',"%".trim($_REQUEST['logino'])."%");

        if( $_REQUEST['phone'] != '' )
          $map['phone'] = array('like',"%".trim($_REQUEST['phone'])."%");

        if( $_REQUEST['mobile'] != '' )
          $map['mobile'] = array('like',"%".trim($_REQUEST['mobile'])."%");

        if( $_REQUEST['address'] != '' )
          $map['address'] = array('like',"%".trim($_REQUEST['address'])."%");

        if( $_REQUEST['shipping_name'] != '' )
          $map['shipping_name'] = array('like',"%".trim($_REQUEST['shipping_name'])."%");

        if( $_REQUEST['customer_name'] != '' )
          $map['customer_name'] = array('like',"%".trim($_REQUEST['customer_name'])."%");


        $key = trim($_REQUEST['keywords']);
        if(!empty($key)) {
                $where['Sale_detail.sale_title'] = array('like',"%".$key."%");//产品名称
            //$where['_logic'] = "or";
            $map['_complex'] = $where;
        }
        if(!empty($_REQUEST['order_no'])) {
            $key2 = trim($_REQUEST['order_no']);
            if(!empty($_REQUEST['keywords']) || ($_REQUEST['etype'] == 'detail') )
              $map['_string'] = '(Sale.sale_no like "%'.$key2.'%")  OR ( Sale.mall_no like "%'.$key2.'%") ';
            else
              $map['_string'] = '(sale_no like "%'.$key2.'%")  OR ( mall_no like "%'.$key2.'%") ';
        }

        

        if( $_REQUEST['order_source_id'] != '' )
          $map['order_source_id'] = $_REQUEST['order_source_id'];
        
        if( $_REQUEST['logicompany_id'] != '' )
          $map['logicompany_id'] = $_REQUEST['logicompany_id'];
        if($_REQUEST['logicompany_id'] == -1 )
          $map['logicompany_id'] = 0;
        if($_REQUEST['except_logicompany_id'] != "" )
          $map['logicompany_id'] = array('neq',$_REQUEST['except_logicompany_id']);
        //time 
        $cond_time = array();
        if( $_REQUEST['start_time'] != '' )
          array_push($cond_time, array( 'egt' , strtotime($_REQUEST['start_time']) ) );
          //$cond_time = array( 'egt' , strtotime($_REQUEST['start_time']) );
        if( $_REQUEST['end_time'] != '' )
          array_push($cond_time, array( 'elt' , strtotime($_REQUEST['end_time']) ) );

        //选择了时间类型,并且时间不为空，则按时间进行搜索
        if( $_REQUEST['time_type'] != "" && 
          ($_REQUEST['end_time'] != '' ||  $_REQUEST['start_time'] != '' ) ){
            switch ($_REQUEST['time_type']) {
              case '1': //审核时间
                $map['check_time '] = $cond_time;
                break;
              case '2': //发货时间
                $map['shipping_time '] = $cond_time;
                break;
              case '3': //下单时间
                if (empty($_REQUEST['keywords'])) {
                    
                    if($_REQUEST['etype'] == 'detail' ){ //导出订单详情，需按saleView进行搜索
                      $map['Sale.create_time '] = $cond_time;
                    }else
                      $map['create_time '] = $cond_time;
                }else
                    $map['Sale.create_time '] = $cond_time;
                break;
              case '4': //支付时间
                $map['pay_time '] = $cond_time;
                break;
              default:  //按下单时间查询
                $map['create_time '] = $cond_time;
                break;
            }
            
        }

        if( $_REQUEST['order_status'] != '' )
          $map['order_status'] = $_REQUEST['order_status'];
        else
            $map['order_status'] = 2; //to shipping
        
        if( $_REQUEST['status'] != '' )
          $map['status'] = $_REQUEST['status'];
        else
            $map['status'] = 1; //checked
        $map['prepare_status'] = 1; //货齐已打印

        if( $_REQUEST['warehouse_id'] == '' )
            $map['warehouse_id'] = 1; //默认同普仓库
        else
            $map['warehouse_id'] = $_REQUEST['warehouse_id'];
    }

     public function  index() {
        $map = $this->_search ();
        if (method_exists ( $this, '_filter' )) {
            $this->_filter ( $map );
        }
        if(empty($_REQUEST['keywords']) ){
          
          if(!empty($_GET)){
            //pass parameters to export_order function
            $parameters = str_replace(__URL__.'?', '', __SELF__);
            $this->assign('parameters' ,$parameters);
          }
          parent::index('Sale',800);
        }else{ //view视图展示
            $model = D ('SaleView');
            if (! empty ( $model )) {
                $this->_list(D('SaleView'), $map, $sortBy = 'create_time desc', $asc = false,true,800);
            }
            //pass parameters to export_order function
            $parameters = str_replace(__URL__.'?', '', __SELF__);
            $this->assign('parameters' ,$parameters);
            $this->display ();
            return;
        }
    }

public function update()
{
    A('Sale')->update();
}

public function edit()
{
   parent::edit('Sale');
}

public function out_stock_log(){
   if(empty($_POST['sale_id']) || empty( $_POST['sale_detail_id']) )
     parent::edit('Sale','Prepare:out_stock_log');    
   else{
     $sid =  M('Sale')->where('id = '.$_POST['sale_id'])->setField('prepare_status',2);//缺货己打印 
     $sdid =  M('Sale_detail')->where('id = '.$_POST['sale_detail_id'])->setField('prepare_status',2);//缺货己打印 
     if($sid || $sdid){
         $message = "缺货登记订单编号".$_POST['sale_id'].",商品明细ID ".$_POST['sale_detail_id'];
         A('Action')->writeLog($message,"缺货登记","Sale_detail",$_POST['sale_detail_id'] );
         $this->success("缺货登记成功！请登记物流信息！",false,1);
     }
     else
         $this->error('缺货登记失败或已经登记，请重试！',false,6);
    }
   
}
    //导入快递单和订单号进行快速匹配
    public function import_order_express($tpl="import_order_express"){
    	if(($_FILES['upload']['name'] == '') ){
          $this->display($tpl);
          return;
      }
      if(empty($_POST['logicompany_id']))
          $this->error("请选择快递公司!");
      $logicompany_id = $_POST['logicompany_id'];    

       // $sheetData = A('Import')->getExcel();
        $sale = M('Sale');
        $k = 0; //count import record
        $sdata = array();
        $affect_orders = ""; // maybe affect orders
       
        $inputFileName = A('Import')->getCsv();
        $row = 1;
        $sheetData = array();
        if (($handle = fopen($inputFileName, "r")) !== FALSE) {
          while (($data = fgetcsv($handle, 0, ',', '"', '"')) !== FALSE) {
            $sheetData[$row] = $data;
            $row ++;
          }
        }

      //图省事，还是借用下面的sheetData 原来的getExcel方法先保留下面的
        foreach ($sheetData as $key => $value) {
            if ($key > 1) {//从第二行开始读取
                if(empty($value['0']) || empty($value['1']) )
                   continue;
            //TODO 1 check sale_no if exist,  2 check logino is correct 3. check sale status:toshipping,has printed

              if(!is_logino( trim($value['1']), $logicompany_id ))
                  continue; //快递单号不合法，跳出 
             $affect_orders .= ','.trim($value['0']);
            //合并订单拆分
               $snos = explode(',',trim($value['0']) );
               $count_togorder = count($snos ) ;
               if($count_togorder >1 ){//合并订单
                  foreach($snos as $i=> $single_no  ){
                     $k += $i;                 
                     $sdata[$k] = array(
                       'sale_no' => $single_no,   //订单号
                       'logino' => trim($value['1']),   //快递单号
                       'logicompany_id' => $logicompany_id,
                     );
                  } 
               }else
                  $sdata[$k] = array(
                   'sale_no' => trim($value['0']),   //订单号
                   'logino' => trim($value['1']),   //快递单号
                   'logicompany_id' => $logicompany_id,
                  );
               $k++; 
        }
      }
      $tmp_ctable_sql = "create temporary table vm_tmp_order (id int(11) NOT NULL auto_increment PRIMARY KEY, sale_no varchar(100),logicompany_id smallint(3),logino varchar(30) ) DEFAULT CHARSET=utf8;";
      M()->execute($tmp_ctable_sql);
      $tmp_order = M('Tmp_order');
      $count_tmp = $tmp_order->addAll( $sdata );
      if(!$count_tmp)
          $this->error("导入数据出错,可能订单号不是文本形式，或快递单号不合法！");
      
      $count_update = 0;
      //只更新审核通过，待发货，且配货状态为：货齐已打印的订单
      //14-08-07去掉配货状态的限制,以方便代售订单的导入
      $update_sql = "Update vm_sale s,vm_tmp_order t set s.logicompany_id = t.logicompany_id, s.logino = t.logino where s.sale_no = t.sale_no and s.order_status = 2 and s.status = 1 ";
      if($_SESSION['warehouse_id'] != 1 )//非大眼窝用户 ,则控制所属仓库
          $update_sql .=" and warehouse_id = ". $_SESSION['warehouse_id'];
      $count_update = M()->execute($update_sql);
      //京卫订单号可能存在仍是淘宝订单号的问题，其内部单号可能刚刚创建.取临时表订单号与订单表中的原单号匹配
      $update_jw_sql = "Update vm_sale s,vm_tmp_order t set s.logicompany_id = t.logicompany_id, s.logino = t.logino where s.mall_no = t.sale_no and s.order_status = 2  and s.status = 1 ";
      if($_SESSION['warehouse_id'] != 1 )//非大眼窝用户 ,则控制所属仓库
          $update_jw_sql .=" and warehouse_id = ". $_SESSION['warehouse_id'];
      $count_update2 = M()->execute($update_jw_sql);
        //drop tmp table
        M()->execute('Drop table vm_tmp_order');
       $this->assign('jumpUrl','__URL__'); 
       $express = S('express');
       $count_update += $count_update2;
       if( $count_update > 0 )
           A('Action')->writeLog("成功导入 ".$count_update." 条".$express[$logicompany_id]['name']. " 物流信息,导入的订单号：".$affect_orders,'修改','Prepare');
      $this->success('成功导入 '.$count_update.' 条订单物流信息',false,5);
} 
    //对配货中的订单进行自动发货
    public function auto_doshipping(){

        ignore_user_abort();//关掉浏览器，PHP脚本也可以继续执行.
        set_time_limit(3000);// 时间约一小时

        $prepare_map = array(
           'logino' => array('neq', ''),
           'logicompany_id' => array( 'gt',0 ),
           'order_status' => 2, //to shipping
           'status' => 1 //checked orders
        );
        if($_SESSION['warehouse_id'] != 1 )//非大眼窝用户 ,则控制所属仓库
            $prepare_map['warehouse_id'] = $_SESSION['warehouse_id'];
        else
            $prepare_map['prepare_status'] = 1; //大眼窝仓库必须是货配齐后才能自动发货,代售仓不受限制.

       $sale_orders = M('Sale')->where($prepare_map )->field('id,order_source_id,sale_no,logino,logicompany_id,mobile')->findAll();    
       if(!is_array($sale_orders))
           $this->error('暂无订单需要自动发货！');
       //系统自身发货
       $shipping_data = array(
           'shipping_time' => time(),
           'order_status' => 3, //已发货
       );

        //检查库存，库存不足，不能发货TODO
       // A('Sale')->check_stock($id); //检查库存 每个订单号单独查
       //TODO check logino
       $count_shipping = M('Sale')->where($prepare_map )->save($shipping_data);    
       
       if($count_shipping < 0 ){
          $this->error("发货出现错误，请重发"); 
           
       }


       $order_api = A('OrderAPI');
       $express = S('express');
       $sale_action = A('Sale');
       //第三方平台发货
       $change_sale_nos = "";
       $change_sale_ids = "";
       foreach ($sale_orders as $value) {
            $change_sale_nos .="," .$value['sale_no'];
            $change_sale_ids .=",". $value['id'];

            //decrease stock
            $sale_action->update_sale_stock($value['id']);
           //德生堂订单
           if($value['order_source_id'] == 5 ||  $value['order_source_id'] == 6 ||  $value['order_source_id'] == 8 ||  $value['order_source_id'] == 10){
               $order_api->dst_shipping($value['sale_no'],$value['logino'],$value['logicompany_id']);
              //发货短信通知
                $express = S('express');
                A('Sale')->shipping_notice($value['mobile'] , $express[$value['logicompany_id']]['name'],$value['logino'], $value['order_source_id']);
           }
          else if( $value['order_source_id'] < 4 )//京卫订单
               jw_shipping( $value['sale_no'],$express[$value['logicompany_id']]['name'],$value['logino'],$value['logicompany_id'],$value['order_source_id'],$value['mobile'] );
          
          sleep(1);
       }
       //记录大批量自动发货日志以备查
      A('Action')->writeLog("自动发货".$count_shipping. "订单,单号（".$change_sale_nos."),ID(".$change_sale_ids.")",'修改','Prepare',$change_sale_ids);
      $this->success('自动发货 '.$count_shipping.' 条订单',false,15);
    }


}
?>
